package net.qiqbframework.common.dto;

import lombok.Getter;
import lombok.NonNull;
import lombok.Setter;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Objects;
import java.util.function.Function;

/**
 * 分页结果
 *
 * @param <T>
 */
public class PageResultDto<T> implements Serializable {

    public static final int DEFAULT_PAGE_SIZE = 20;
    /**
     * 页数
     */
    @Getter
    @Setter
    private long pageNumber;

    /**
     * 一页的数量
     */
    @Getter
    @Setter
    private int pageSize;

    /**
     * 总数量
     */
    @Getter
    @Setter
    private long total;

    @Getter
    @Setter
    private ArrayList<T> records = new ArrayList<>();

    public PageResultDto() {
        this(1, DEFAULT_PAGE_SIZE);
    }

    public PageResultDto(PageParamDto param) {
        this(param.getPageNumber(), param.getPageSize());
    }

    public PageResultDto(long pageNumber, int pageSize) {

        this.pageNumber = Math.max(pageNumber, 0);
        this.pageSize = pageSize <= 0 ? DEFAULT_PAGE_SIZE : pageSize;
    }

    public PageResultDto(long pageNumber, int pageSize, long total) {
        this(pageNumber, pageSize);
        this.total = total;

    }


    public <U> PageResultDto<U> map(@NonNull Function<? super T, U> wrapper) {
        Objects.requireNonNull(wrapper);
        final PageResultDto<U> r = new PageResultDto<>(this.pageNumber, this.pageSize, this.total);
        r.getRecords().addAll(this.getRecords().stream().map(wrapper).toList());
        return r;
    }
}